/**
 * org.vz.product.collect.maintain.config
 * @since : jdk 1.8
 */
package org.vz.product.collect.maintain.config;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.jms.JMSException;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.command.BrokerInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Primary;
import org.springframework.jms.core.JmsMessagingTemplate;
import org.vz.product.collect.maintain.util.StringUtil;

/**
 * @author      chenhuaijin
 * @CreateTime  2017年9月14日 上午10:57:07
 * @version     1.0.0
 * @description activemq集群的计算机名与ip的映射
 */
@ConfigurationProperties(prefix="spring.acqcluster")
@Primary
public class AcqclusterConfig {
	@Autowired
    JmsMessagingTemplate jmsMessagingTemplate;
	private String[] names;
	private String[] addrs;
	public static String previousHostName;
	/**
	 * @return the names
	 */
	public String[] getNames() {
		return names;
	}
	/**
	 * @param names the names to set
	 */
	public void setNames(String[] names) {
		this.names = names;
	}
	/**
	 * @return the addrs
	 */
	public String[] getAddrs() {
		return addrs;
	}
	/**
	 * @param addrs the addrs to set
	 */
	public void setAddrs(String[] addrs) {
		this.addrs = addrs;
	}
	/**
	 * 
	 * @description  按规则拼接字符串
	 * @author       chenhuaijin
	 * @CreateTime   2017年9月14日 上午11:41:36
	 * @return
	 */
	public String ruleString(){
		List<String> list =  StringUtil.arrayToList(this.addrs);
		String str = StringUtil.listToString(list, ":2181,")+":2181";//ip1:2181,ip2:2181
		return str;
	}
	/**
	 * 
	 * @description  将ip与计算机名进行映射
	 * @author       chenhuaijin
	 * @CreateTime   2017年9月14日 下午2:40:55
	 * @return
	 */
	public Map<String,String> mapNameIp(){
		Map<String,String> map = new HashMap<String, String>();
		int len = this.names.length;
		for(int i=0;i<len;i++){
			map.put(this.names[i], this.addrs[i]);
		}
		return map;
	}
	
	public void init() throws JMSException{
		ActiveMQConnectionFactory conn =  (ActiveMQConnectionFactory)(jmsMessagingTemplate.getConnectionFactory());
	   	ActiveMQConnection an = null;
	
		an = (ActiveMQConnection)(conn.createConnection());
		an.start();
		BrokerInfo bi =	an.getBrokerInfo();
		String brokerUrl = bi.getBrokerURL();//得到当前连接的集群的url形如：tcp://pcName:port
		an.stop();
		String pcName = StringUtil.substringBetween(brokerUrl, "//",":");
		previousHostName = pcName;
		
	}
}
